package com.wl.org.controller;

import com.wl.basic.util.AjaxResult;
import com.wl.basic.util.PageList;
import com.wl.org.domain.Department;
import com.wl.org.query.DepartmentQuery;
import com.wl.org.service.DepartmentService;
import com.wl.system.annotation.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//这个注解就是@controller 和  @ResponseBody 组合注解
@RequestMapping("/department")//请求路径
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    //查单个  @PathVariable("id")Long id参数需要加上
    @GetMapping("/{id}")
    public Department findById(@PathVariable("id")Long id){
        return departmentService.loadById(id);
    }

    //查询所有  不需要参数就不要@PathVariable来写参数
    @GetMapping()
    public List<Department> findAll(){
        return departmentService.loadAll();
    }
    //删除
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除",sn = "department:delete")
    public AjaxResult deleteById(@PathVariable("id")Long id){
        try {
            //执行删除
            departmentService.remove(id);
            //成功返回结果  默认是成功就使用无参构造就行
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            //失败就返回结果集 调用全参构造自己赋值
            return new AjaxResult(false,"删除失败");
        }
    }
    //新增和修改
    @PutMapping
    @PreAuthorize(name = "部门新增and修改",sn = "department:save")
    public AjaxResult addAanUpt(@RequestBody Department department){
        try {
            //获取department的id
            if(department.getId() == null){
                //执行新增
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            //成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            return new AjaxResult(false,"操作失败");
        }
    }

    //分页
    @PostMapping
    @PreAuthorize(name = "分页",sn = "department:list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }


    //批量删除
    @PatchMapping
    @PreAuthorize(name = "部门批量删除",sn = "department:patchDel")
    public AjaxResult removeA(@RequestBody List<Long>ids){
        try {
            //执行删除
            departmentService.removeA(ids);
            //成功返回结果  默认是成功就使用无参构造就行
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            //失败就返回结果集 调用全参构造自己赋值
            return new AjaxResult(false,"删除失败");
        }
    }

    //无限级树
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

}
